/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.MRSAdminManagerBeanRemote;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author cuilin
 */
public class StudentClientServlet extends HttpServlet {

    @EJB
    private MRSAdminManagerBeanRemote mrs;
    private String page;
    private String reqfunction;
    private String msg;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        System.out.println("request.getPathInfo():" + request.getPathInfo());
        if (null == request.getPathInfo() || request.getPathInfo().equals("") || "".equals(request.getPathInfo().substring(1))) {
            page = "login";
        } else {
            page = request.getPathInfo().substring(1);
        }

        System.out.println("request.getPathInfo():" + page);

        reqfunction = request.getParameter("reqfunction");

        System.out.println("reqfunction:" + reqfunction);
        if (null != reqfunction && !"".equals(reqfunction)) {
            if ("login".equalsIgnoreCase(page)) {
                login(request, response);
            } else if ("logout".equalsIgnoreCase(page)) {
                logout(request, response);
            } else if ("profile".equalsIgnoreCase(page)) {
                if ("changepassword".equalsIgnoreCase(reqfunction)) {
                    changePassword(request, response);
                } else if ("changeemail".equalsIgnoreCase(reqfunction)) {
                    changeEmail(request, response);
                }

            } else if ("module".equalsIgnoreCase(page)) {
                if ("modulesearch".equalsIgnoreCase(reqfunction)) {
                    searchModules(request, response);
                } else {
                    registeration(request, response);
                }
            }
        } else if ("mymodules".equalsIgnoreCase(page)) {
            myModules(request, response);
        }
        sendRedirect(request, response);
    }

    private void myModules(HttpServletRequest request, HttpServletResponse response) {

        updateSessionData(request, response);
    }

    private void registeration(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession(false);


        String timeslot = request.getParameter("timeslot");
        boolean regAvailable = true;
        boolean regscuccess = false;
        List mytimetables = null;
        
        updateSessionData(request, response);
        if (null != request.getAttribute("timetables")) {
            mytimetables = (List) request.getAttribute("timetables");
            if (mytimetables.contains(timeslot)) {
                msg = "Time table clash";
                regAvailable = false;
            }
        }

        if (regAvailable) {
            Long studentId = (Long) session.getAttribute("id");
            Long moduleid = Long.parseLong(request.getParameter("moduleid").toString());
            if ("modulereg".equalsIgnoreCase(reqfunction)) {
                mrs.assignStudentModule(studentId, moduleid);
            } else if ("tutorialreg".equalsIgnoreCase(reqfunction)) {

                String mreg = request.getParameter("mreg");
                if ("false".equals(mreg)) {
                    mrs.assignStudentModule(studentId, moduleid);
                }
                Long tutorialid = Long.parseLong(request.getParameter("tutorialid").toString());
                mrs.assignStudentTutorial(studentId, tutorialid);
            }

            regscuccess = true;
            updateSessionData(request, response);
        }

        request.setAttribute("regscuccess", regscuccess);
        request.setAttribute("msg", msg);

    }

    private void searchModules(HttpServletRequest request, HttpServletResponse response) {
        String searchtype = request.getParameter("searchtype");


        String modulecode = request.getParameter("modulecode");
        // Retrieve the value of the query parameter "password" (from password field)
        String moduletitle = request.getParameter("moduletitle");

        boolean scuccess = false;

        if ("mcode".equals(searchtype) && (modulecode == null || modulecode.equals(""))) {
            msg = "module code can not empty";
        } else if ("mtitle".equals(searchtype) && (moduletitle == null || moduletitle.equals(""))) {
            msg = "module title can not empty";
        } else {
            List modules = mrs.findModuleEntities(modulecode, moduletitle);
            if (null == modules || modules.isEmpty()) {
                msg = "modules not found";
            } else {
                request.setAttribute("modules", modules);
                updateSessionData(request, response);
                scuccess = true;
                System.out.println("modules:" + modules.size());
            }
        }

        request.setAttribute("scuccess", scuccess);
        request.setAttribute("msg", msg);
    }

    private void changePassword(HttpServletRequest request, HttpServletResponse response) {
        // Retrieve the value of the query parameter "password" (from password field)
        String oldpassword = request.getParameter("oldpassword");
        // Retrieve the value of the query parameter "password" (from password field)
        String newpassword = request.getParameter("newpassword");

        HttpSession session = request.getSession(false);
        String matricnumber = session.getAttribute("matricnumber").toString();
        boolean scuccess = false;
        // Get null if the parameter is missing from query string.
        // Get empty string or string of white spaces if user did not fill in
        if (oldpassword == null || oldpassword.equals("")) {
            msg = "old password can not empty";
        } else if (newpassword == null || newpassword.equals("")) {
            msg = "new password can not empty";
        } else {
            List student = mrs.findStudent(matricnumber);
            if (null == student || student.isEmpty()) {
                msg = "session timout, please re login system";
            } else if (oldpassword.equals(student.get(2))) {
                mrs.updateStudent((Long) student.get(0), newpassword, null);
                scuccess = true;
                msg = "changed password success";
                System.out.println("logined:" + matricnumber);
            } else {
                msg = "invalid existing password";
            }

        }

        request.setAttribute("scuccess", scuccess);
        request.setAttribute("msg", msg);
    }

    private void changeEmail(HttpServletRequest request, HttpServletResponse response) {
        String email = request.getParameter("email");
        String newemail = request.getParameter("newemail");

        HttpSession session = request.getSession(false);
        String matricnumber = session.getAttribute("matricnumber").toString();
        boolean scuccess = false;
        // Get null if the parameter is missing from query string.
        // Get empty string or string of white spaces if user did not fill in
        if (email == null || email.equals("")) {
            msg = "existing email can not empty";
        } else if (newemail == null || newemail.equals("")) {
            msg = "new email can not empty";
        } else {
            List student = mrs.findStudent(matricnumber);
            if (null == student || student.isEmpty()) {
                msg = "session timout, please re login system";
            } else if (email.equals(student.get(3))) {
                mrs.updateStudent((Long) student.get(0), null, newemail);
                scuccess = true;
                msg = "changed email success";
                System.out.println("logined:" + matricnumber);
            } else {
                msg = "invalid existing email";
            }

        }
        request.setAttribute("scuccess", scuccess);
        request.setAttribute("msg", msg);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) {

        // Retrieve the value of the query parameter "username" (from text field)
        String matricnumber = request.getParameter("matricnumber");
        // Retrieve the value of the query parameter "password" (from password field)
        String password = request.getParameter("password");

        HttpSession session = request.getSession(true);

        System.out.println("start login :" + matricnumber);

        boolean logined = false;
        // Get null if the parameter is missing from query string.
        // Get empty string or string of white spaces if user did not fill in
        if (matricnumber == null || matricnumber.equals("")) {
            msg = "matric number can not empty";
        } else if (password == null || password.equals("")) {
            msg = "matric number can not empty";
        } else {

            List student = mrs.findStudent(matricnumber);
            //List student = null;
            //System.out.println("student id:" + student.get(0));
            //System.out.println("student ps:" + student.get(2));
            if (null == student || student.isEmpty()) {
                msg = "matric number not found";
            } else if (password.equals(student.get(2))) {
                session.setAttribute("id", student.get(0));
                session.setAttribute("matricnumber", matricnumber);

                logined = true;
                msg = "logined success";
                System.out.println("logined:" + matricnumber);
            } else {
                msg = "invalid password";
            }

        }
        request.setAttribute("logined", logined);
        request.setAttribute("msg", msg);
        if (!logined) {
            if (null != session) {
                session.removeAttribute("matricnumber");
            }
        }
    }

    /**
     * to initial session with current user data create time table list, for
     * identity current time slots
     *
     * @param request
     * @param response
     */
    private void updateSessionData(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession();
        String id = session.getAttribute("id").toString();
        
        List modules = mrs.findStudentModules(Long.parseLong(id));

        //to create time table list, for identity current time slots
        if (null != modules) {
            //story student's modules to session
            request.setAttribute("mymodules", modules);
            List tutorialids = new ArrayList();
            List moduleids = new ArrayList();
            List timetables = new ArrayList();
            for (Object m : modules) {
                List md = (List) m;
                moduleids.add(md.get(0));
                timetables.add(md.get(1));
                if (null != md.get(6)) {
                    List tuts = (List) md.get(6);
                    for (Object t : tuts) {
                        List mt = (List) t;
                        tutorialids.add(mt.get(0));
                        timetables.add(mt.get(1));
                    }
                }
            }
            request.setAttribute("moduleids", moduleids);
            request.setAttribute("tutorialids", tutorialids);
            request.setAttribute("timetables", timetables);
        } else {
            System.out.println("refresh student fail ");
        }

        System.out.println("refresh student for " + id);

    }

    private void logout(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session = request.getSession(false);
        if (null != session) {
            session.removeAttribute("matricnumber");
        }

        request.setAttribute("logined", false);
        request.setAttribute("msg", "Logout success");
    }

    private void sendRedirect(HttpServletRequest request, HttpServletResponse response) {
        try {
            String path = request.getHeader("Referer");

            System.out.println("request header Referer:" + path);
            //RequestDispatcher dispatcher = request.getRequestDispatcher("/"+page + ".jsp");
            //request.getRequestDispatcher(page);
            RequestDispatcher dispatcher = getServletContext().getNamedDispatcher(page);
            if (null == dispatcher) {
                dispatcher = getServletContext().getNamedDispatcher("index");
            }
            dispatcher.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(StudentClientServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(StudentClientServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
}
